package com.jy.oms.framework.thread;


import com.jy.oms.framework.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 可关闭线程
 *
 * @author liuquan
 */
public abstract class CloseableThread extends Thread {
    protected static Logger logger = LoggerFactory.getLogger(CloseableThread.class);

    protected volatile boolean stoped = false;

    public CloseableThread() {
        CloseableThreadManager manager = SpringUtil.getBean(CloseableThreadManager.class);
        manager.regist(this);
    }

    public void toStop() {
        stoped = true;

        try {
            this.afterStop();
        } catch (Exception e){
        }
    }

    @Override
    public void run() {
        this.beforeRunCloseable();

        while (!stoped) {
            try {
                this.runCloseable();
            } catch (Exception e) {
                if (!stoped) {
                    logger.error("run error.", e);
                }
            }
        }
    }

    protected void beforeRunCloseable() {
    }

    protected void runCloseable() throws Exception {
    }

    protected void afterStop(){
    }
}
